// src/Mine.tsx
import { useState, useEffect, useCallback } from 'react';
import { Layout, Card, Avatar, Typography, Button, Spin, message, Modal } from 'antd';
import { UserOutlined, SettingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Sidebar from '../Sidebar';
import Follower from './Follower';
import Following from './Following';
import Mutualfollowing from './Mutualfollowing';
import Setting from '../settings/Setting';
import Post from './Post';
import Collect from './Collect';
import Browsing from './Browsing';

const { Header, Content } = Layout;
const { Title, Text } = Typography;

interface User {
  id: number;
  username: string;
  avatar?: string;
  followers: number;
  following: number;
  mutualCount: number;
  recipesCount?: number;
}

function Mine() {
  const navigate = useNavigate();
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [followerModalVisible, setFollowerModalVisible] = useState(false);
  const [followingModalVisible, setFollowingModalVisible] = useState(false);
  const [mutualModalVisible, setMutualModalVisible] = useState(false);
  const [settingModalVisible, setSettingModalVisible] = useState(false);
  
  // 控制各个组件的显示模式
  const [postShowAll, setPostShowAll] = useState(false);
  const [collectShowAll, setCollectShowAll] = useState(false);
  const [browsingShowAll, setBrowsingShowAll] = useState(false);

  // 获取真实的互关数量
  const fetchMutualCount = useCallback(async (userId: number, token: string): Promise<number> => {
    try {
      // 并行获取关注列表和粉丝列表
      const [followeesResponse, followersResponse] = await Promise.all([
        fetch(`/api/userfollows/follower/${userId}/followees`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        }),
        fetch(`/api/userfollows/followee/${userId}/followers`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        })
      ]);

      if (followeesResponse.ok && followersResponse.ok) {
        const followees = await followeesResponse.json();
        const followers = await followersResponse.json();
        
        // 提取关注和被关注的用户ID
        const followeeIds = new Set(followees.map((item: any) => item.followeeId));
        const followerIds = new Set(followers.map((item: any) => item.followerId));
        
        // 计算交集：既是关注的人又是粉丝的人
        const mutualUserIds = [...followeeIds].filter(id => followerIds.has(id));
        console.log('互关用户计算:', {
          followeeCount: followeeIds.size,
          followerCount: followerIds.size,
          mutualCount: mutualUserIds.length
        });
        return mutualUserIds.length;
      }
      return 0;
    } catch (error) {
      console.error('获取互关数量失败:', error);
      return 0;
    }
  }, []);

  // 更新关注数量
  const updateFollowCounts = useCallback(async (userId: string): Promise<{ followCount: number; followerCount: number; mutualCount: number }> => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return { followCount: 0, followerCount: 0, mutualCount: 0 };

      let followCount = 0;
      let followerCount = 0;
      let mutualCount = 0;

      // 分别获取各个数据
      try {
        const followCountResponse = await fetch(`/api/userfollows/follower/${userId}/count`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });
        if (followCountResponse.ok) {
          const data = await followCountResponse.json();
          followCount = typeof data === 'number' ? data : data.count || 0;
        }
      } catch (error) {
        console.error('获取关注数量失败:', error);
      }

      try {
        const followerCountResponse = await fetch(`/api/userfollows/followee/${userId}/count`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });
        if (followerCountResponse.ok) {
          const data = await followerCountResponse.json();
          followerCount = typeof data === 'number' ? data : data.count || 0;
        }
      } catch (error) {
        console.error('获取粉丝数量失败:', error);
      }

      // 获取真实的互关数量
      try {
        mutualCount = await fetchMutualCount(parseInt(userId), token);
      } catch (error) {
        console.error('获取互关数量失败:', error);
      }

      console.log('关注数量更新结果:', { followCount, followerCount, mutualCount });

      return { followCount, followerCount, mutualCount };

    } catch (error) {
      console.error('更新关注数量失败:', error);
      return { followCount: 0, followerCount: 0, mutualCount: 0 };
    }
  }, [fetchMutualCount]);

  const fetchUserData = useCallback(async () => {
    try {
      setLoading(true);
      const userId = localStorage.getItem('userId');
      const token = localStorage.getItem('token');

      if (!userId || !token) {
        message.error('请先登录');
        navigate('/');
        return;
      }

      // 并行获取用户信息和关注数量
      const [userResponse, followCounts] = await Promise.all([
        fetch(`/api/users/${userId}`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        }),
        updateFollowCounts(userId)
      ]);

      if (!userResponse.ok) {
        throw new Error(`获取用户信息失败: ${userResponse.status}`);
      }

      const userData = await userResponse.json();

      if (!userData.id || !userData.username) {
        throw new Error('用户数据不完整');
      }

      // 使用从 API 获取的关注数量，而不是 userData 中的旧数据
      setUser({
        id: userData.id,
        username: userData.username,
        avatar: userData.avatar ? `http://218.244.141.86:8080${userData.avatar}` : undefined,
        followers: followCounts.followerCount,
        following: followCounts.followCount,
        mutualCount: followCounts.mutualCount,
      });

    } catch (error) {
      console.error('加载用户信息失败:', error);
      if (error instanceof Error) {
        message.error(`加载失败: ${error.message}`);
      } else {
        message.error('网络错误，请检查连接');
      }
      setUser(null);
    } finally {
      setLoading(false);
    }
  }, [navigate, updateFollowCounts]);

  // 只在组件挂载时获取用户数据
  useEffect(() => {
    fetchUserData();
  }, [fetchUserData]);

  // 刷新关注数量
  const refreshFollowCounts = useCallback(async () => {
    const userId = localStorage.getItem('userId');
    if (userId && user) {
      try {
        console.log('开始刷新关注数量...');
        const followCounts = await updateFollowCounts(userId);
        console.log('刷新后的关注数量:', followCounts);
        
        setUser(prev => prev ? {
          ...prev,
          followers: followCounts.followerCount,
          following: followCounts.followCount,
          mutualCount: followCounts.mutualCount
        } : null);
        
        message.success('关注状态已更新');
      } catch (error) {
        console.error('刷新关注数量失败:', error);
        message.error('刷新关注状态失败');
      }
    }
  }, [updateFollowCounts, user]);

  const handleUserUpdate = useCallback(() => {
    fetchUserData();
  }, [fetchUserData]);

  const renderSettingsModal = () => (
    <Modal
      title="我的设置"
      open={settingModalVisible}
      onCancel={() => setSettingModalVisible(false)}
      footer={null}
      width={500}
      style={{ top: 20 }}
      styles={{
        content: {
          backgroundColor: '#fdf6e9',
          borderRadius: '12px',
        },
        body: {
          backgroundColor: '#fdf6e9',
          padding: 0,
          borderRadius: '12px',
        },
        header: {
          backgroundColor: '#fdf6e9',
          borderBottom: '1px solid #e8d5b5',
          borderRadius: '12px 12px 0 0',
        }
      }}
    >
      <Setting onUserUpdate={handleUserUpdate} />
    </Modal>
  );

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        backgroundImage: "url('/background2.jpg')",
        backgroundSize: 'cover'
      }}>
        <Spin size="large" />
        <div style={{ marginLeft: 16 }}>加载中...</div>
      </div>
    );
  }

  if (!user) {
    return (
      <div style={{ 
        padding: 40, 
        textAlign: 'center',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        height: '100vh',
        backgroundImage: "url('/background2.jpg')",
        backgroundSize: 'cover'
      }}>
        <div style={{ marginBottom: 20 }}>
          <Text style={{ fontSize: 16, color: '#ff4d4f' }}>无法加载用户信息</Text>
        </div>
        <Button 
          type="primary" 
          onClick={() => navigate('/')}
          style={{
            backgroundColor: '#e8d9c7',
            borderColor: '#e8d9c7',
            color: '#555',
          }}
        >
          返回登录页
        </Button>
      </div>
    );
  }

  return (
    <Layout style={{ 
      minHeight: '100vh', 
      backgroundImage: "url('/background2.jpg')",
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundAttachment: 'fixed'
    }}>
      <Sidebar />

      <Layout style={{ background: 'transparent' }}>
        <Header style={{
          background: 'white',
          boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
          padding: '0 40px',
          height: 'auto',
          lineHeight: '64px',
          borderRadius: '12px 12px 0 0',
          margin: '20px 40px 0 40px'
        }}>
          <Title level={2} style={{ margin: 0 }}>我的</Title>
        </Header>

        <Content style={{ 
          margin: '0 40px 20px 40px',
          padding: '0',
          background: 'transparent',
          borderRadius: '0 0 12px 12px',
          overflow: 'auto',
          maxHeight: 'calc(100vh - 100px)'
        }}>
          <div style={{
            background: 'white',
            padding: '30px',
            borderRadius: '0 0 12px 12px',
            minHeight: '100%'
          }}>
            <Card 
              style={{ 
                marginBottom: '24px',
                background: 'rgba(255, 253, 248, 0.9)',
                border: '1px solid #e8d5b5',
                borderRadius: '12px'
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
                <Avatar size={80} src={user.avatar} icon={<UserOutlined />} />
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Title level={4} style={{ margin: 0, color: '#8b4513' }}>{user.username}</Title>
                    <Button 
                      icon={<SettingOutlined />}
                      style={{
                        backgroundColor: '#e8d9c7',
                        borderColor: '#e8d9c7',
                        color: '#555',
                        borderRadius: '20px'
                      }}
                      onClick={() => setSettingModalVisible(true)}
                    >
                      我的设置
                    </Button>
                  </div>
                  {/* 删除个人简介部分 */}
                  <div style={{ display: 'flex', gap: '20px', marginTop: '12px' }}>
                    <Text 
                      style={{ color: '#8b4513', cursor: 'pointer' }}
                      onClick={() => setMutualModalVisible(true)}
                    >
                      <strong>{user.mutualCount}</strong> 互关
                    </Text>
                    <Text 
                      style={{ color: '#8b4513', cursor: 'pointer' }}
                      onClick={() => setFollowerModalVisible(true)}
                    >
                      <strong>{user.followers}</strong> 粉丝
                    </Text>
                    <Text 
                      style={{ color: '#8b4513', cursor: 'pointer' }}
                      onClick={() => setFollowingModalVisible(true)}
                    >
                      <strong>{user.following}</strong> 关注
                    </Text>
                  </div>
                </div>
              </div>
            </Card>

            {/* 使用独立的组件 */}
            <Post 
              userId={user.id} 
              showAll={postShowAll}
              onShowAllChange={setPostShowAll}
            />
            
            <Collect 
              userId={user.id}
              showAll={collectShowAll}
              onShowAllChange={setCollectShowAll}
            />
            
            <Browsing 
              userId={user.id}
              showAll={browsingShowAll}
              onShowAllChange={setBrowsingShowAll}
            />

            <Follower
              visible={followerModalVisible}
              onClose={() => setFollowerModalVisible(false)}
              userId={user.id}
              onFollowChange={refreshFollowCounts}
            />

            <Following
              visible={followingModalVisible}
              onClose={() => setFollowingModalVisible(false)}
              userId={user.id}
              onFollowChange={refreshFollowCounts}
            />

            <Mutualfollowing
              visible={mutualModalVisible}
              onClose={() => setMutualModalVisible(false)}
              userId={user.id}
              onFollowChange={refreshFollowCounts}
            />

            {renderSettingsModal()}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
}

export default Mine;